package com.kylewang.pomodoro.ui.timer;

import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import ezy.ui.view.RoundButton;

import com.bytedance.scene.group.GroupScene;
import com.dinuscxj.progressbar.CircleProgressBar;
import com.kylewang.pomodoro.R;
import com.kylewang.pomodoro.helper.Utils;
import com.kylewang.pomodoro.model.TaskModel;
import com.kylewang.pomodoro.helper.DBManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;



public class TimerScene extends GroupScene {

    public static class TaskItemClickedEvent {
        public TaskModel item;
    }

    private ViewGroup mRootView;
    private TaskModel currentItem;
    private TextView countdown;
    private CircleProgressBar progressBar;
    private RoundButton gobutton;
    private View currentItemView;
    private Button toggleBtn;

    private Handler mHandler = new Handler();
    private TimerRunnable mRunnable;

    @Override
    public ViewGroup onCreateView(LayoutInflater inflater, ViewGroup container,
                                  Bundle savedInstanceState) {
        mRootView = (ViewGroup) inflater.inflate(R.layout.fragment_timer, container, false);
        return mRootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        countdown = mRootView.findViewById(R.id.textView3);
        progressBar = mRootView.findViewById(R.id.line_progress);
        gobutton = mRootView.findViewById(R.id.button3);
        currentItemView = mRootView.findViewById(R.id.current_task_view);
        currentItemView.setVisibility(View.INVISIBLE);
        toggleBtn = mRootView.findViewById(R.id.toggleButton);
        toggleBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                currentItem.setStatus(2);
                if (currentItem.getTid() != null && currentItem.getTid().length() > 0) {
                    DBManager.updateTask(currentItem);
                }
                stopTimerRunnable();
                resetCurrentTask();
            }
        });

        gobutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Utils.isFastClick()) {
                    return;
                }
                RoundButton btn = (RoundButton) view;
                // current running, need pause
                Boolean currentIsRunning = btn.getText().toString().equals(getString(R.string.pause));
                if (currentIsRunning) {
                    btn.setText(R.string.btn_run);
                    stopTimerRunnable();
                } else {
                    if (currentItem == null) {
                        TaskItemClickedEvent newEvent = new TaskItemClickedEvent();
                        TaskModel item = TaskModel.generateBlankTaskItem();
                        item.setName("Anonymous task");
                        newEvent.item = item;
                        EventBus.getDefault().post(newEvent);
                    }
                    btn.setText(R.string.pause);
                    startTimerRunnable();
                }
            }
        });
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(TaskItemClickedEvent event) {
        stopTimerRunnable();
        currentItem = event.item;
        countdown.setText(currentItem.remindsStr());
        gobutton.setText(R.string.btn_run);
        Double progress = 1 - (Double.valueOf(currentItem.remindsTime()) / Double.valueOf(currentItem.getTarget_time()));
        progressBar.setProgress((int)(progress * 100));
        currentItemView.setVisibility(View.VISIBLE);
        toggleBtn.setText(currentItem.getName());
        Toast.makeText(getActivity(), "Start task: " + currentItem.getName(), Toast.LENGTH_LONG).show();
        Log.i("Event", "onMessageEvent: did receive task item clicked event");
    }

    private void resetCurrentTask() {
        countdown.setText("25:00");
        gobutton.setText(R.string.btn_run);
        progressBar.setProgress(0);
        currentItemView.setVisibility(View.INVISIBLE);
    }

    private void startTimerRunnable() {
        mRunnable = new TimerRunnable();
        currentItem.setStatus(1);
        mHandler.postDelayed(mRunnable, 100);
    }

    private void stopTimerRunnable() {
        mHandler.removeCallbacks(mRunnable);
        if (currentItem != null && currentItem.getTid() != null) {
            DBManager.updateTask(currentItem);
        }
        mRunnable = null;
    }

    private class TimerRunnable implements Runnable {
        @Override
        public void run() {
            long runningTime = currentItem.getElapsed_duration();
            runningTime += 100;
            long reminds = currentItem.getTarget_time() - runningTime;
            if (reminds <= 0) {
                currentItem.setElapsed_duration(currentItem.getTarget_time());
                currentItem.setStatus(2);
                if (currentItem.getTid() != null) {
                    DBManager.updateTask(currentItem);
                }
                resetCurrentTask();
                currentItem = null;
                stopTimerRunnable();
                return;
            }
            currentItem.setElapsed_duration(runningTime);
            Double progress = 1 - (Double.valueOf(reminds) / Double.valueOf(currentItem.getTarget_time()));
            Log.d("progress", "run: " + progress);
            progressBar.setProgress((int)(progress * 100));

            countdown.setText(currentItem.remindsStr());

            mHandler.postDelayed(this, 100);
        }
    }
}
